import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
@WebFilter({"/books","/cart","/cart.jsp","/home.jsp"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpSession session=req.getSession();
        String username=(String) session.getAttribute("username");
        if (username!=null)
        {
            //登录
            filterChain.doFilter(servletRequest,servletResponse);//放行
        }
        else
        {
            servletRequest.setAttribute("msg","请先登录");
            servletRequest.getRequestDispatcher("login.jsp").forward(servletRequest,servletResponse);
        }
    }
}
